# coding=utf-8
from flask_cors import CORS
from flask import Flask, request
from controllers.aiController import aicontroller
from controllers.ydAIController import ydaicontroller
from logging.handlers import TimedRotatingFileHandler
from concurrent_log_handler import ConcurrentRotatingFileHandler
from utils.views import bp_app, bp_cache
import logging
import os

app = Flask(__name__)
app.static_folder = 'static'
# ai接口
app.register_blueprint(aicontroller)
app.register_blueprint(ydaicontroller)
# redis
app.register_blueprint(bp_app)
bp_cache.init_app(app)
CORS(app, resources = r'/*')

# 拦截器 - 校验登录token
@app.before_request
def defore():
    # 登录过滤
    url = request.path
    if '/static/' in url:
        return None
    return None

# @app.errorhandler(Exception)
# def handle_generic_error(error):
#     app.logger.error("触发全局异常:")
#     app.logger.error(error)
#     return  json.dumps({'code':500, 'message':'系统内部错误'})

def main():
    # 设置日志
    app.logger.setLevel(logging.DEBUG)
    # 创建日志目录（如果不存在）
    log_dir = "./log"
    os.makedirs(log_dir, exist_ok=True)
    formatter = logging.Formatter("[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(thread)d] - %(message)s")
    log_filename = os.path.join(log_dir, "aicheck.log")
    # handler = TimedRotatingFileHandler(log_filename, when="midnight", interval=1, backupCount=15,encoding="UTF-8", delay=False, utc=False)
    # 配置并发安全的日志处理器
    handler = ConcurrentRotatingFileHandler(
        log_filename,
        mode='a',
        maxBytes=100*1024*1024,  # 100MB
        backupCount=15,
        encoding="UTF-8"
    )
    # 设置文件名后缀格式为 YYYY-MM-DD
    # handler.suffix = "%Y-%m-%d"
    app.logger.addHandler(handler)
    handler.setFormatter(formatter)
    # app.run(debug=True, host='0.0.0.0',port=443, ssl_context=('./yddpy.com_bundle.pem','./yddpy.com.key'))
    app.run(debug=True,host='0.0.0.0',port=8081)

if __name__ != '__main__':
    gunicorn_logger = logging.getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

if __name__ == '__main__':
    main()